package com.paishen.peiniwan.module.profile;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Build;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.paishen.common.util.BaseUtil;
import com.paishen.peiniwan.App;
import com.paishen.peiniwan.BaseActivity;
import com.paishen.peiniwan.C;
import com.paishen.peiniwan.R;
import com.paishen.peiniwan.frame.PnwOkCallbackAdapter;
import com.paishen.peiniwan.frame.RecyclerAdapter;
import com.paishen.peiniwan.frame.http.PnwHttpManager;
import com.paishen.peiniwan.frame.http.entity.User;
import com.paishen.peiniwan.frame.http.response.HttpRespData;
import com.paishen.common.widget.MaterialHeader;
import com.squareup.okhttp.Request;

import java.util.ArrayList;
import java.util.List;

import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import jp.wasabeef.recyclerview.adapters.AlphaInAnimationAdapter;


public class MainProfileFansLayout extends LinearLayout {

    private final PtrFrameLayout layPtrFrame;
    private final RecyclerView viewRecycler;
    private final LinearLayoutManager layoutManager;
    private final FansAdapter adapter;

    private boolean reqLoad;
    private boolean fetchOver = false;
    private long collect_id = -1;

    public MainProfileFansLayout(Context context) {
        this(context, null);
    }

    public MainProfileFansLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // interrupt click event
            }
        });

        LayoutInflater.from(context).inflate(R.layout.frame_layout_recycler_simple, this);
        // ((ViewGroup) getChildAt(0)).getChildAt(0).setPadding(0, (int) getResources().getDimension(R.dimen.title_height) + (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT ? BaseUtil.getStatusBarHeight() : 0), 0, 0);
        setPadding(0, (int) getResources().getDimension(R.dimen.title_height) + (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT ? BaseUtil.getStatusBarHeight() : 0), 0, 0);

        viewRecycler = (RecyclerView) findViewById(R.id.view_recycler);
        viewRecycler.setLayoutManager(layoutManager = new LinearLayoutManager(getContext()));

        AlphaInAnimationAdapter alphaAdapter = new AlphaInAnimationAdapter(adapter = new FansAdapter());
        viewRecycler.setAdapter(alphaAdapter);
        viewRecycler.setItemAnimator(new DefaultItemAnimator());
        viewRecycler.addItemDecoration(new RecyclerView.ItemDecoration() {
            int spacing = BaseUtil.dip2px(10);

            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                outRect.top = spacing;
            }
        });

        viewRecycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
            private boolean scrollDown = false;

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                scrollDown = dy > 0;
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                switch (newState) {
                    case RecyclerView.SCROLL_STATE_IDLE:
                        int lastVisibleItem = layoutManager.findLastCompletelyVisibleItemPosition();
                        int totalItemCount = layoutManager.getItemCount();
                        if (lastVisibleItem >= (totalItemCount - 1) && scrollDown) {
                            if (!fetchOver) requestUserCollectList(collect_id);
                        }

                        break;
                    case RecyclerView.SCROLL_STATE_DRAGGING:
                        break;
                }
            }
        });

        layPtrFrame = (PtrFrameLayout) findViewById(R.id.lay_ptr_frame);
        MaterialHeader header = new MaterialHeader(getContext());
        int[] colors = new int[]{0xFF05131A};
        header.setColorSchemeColors(colors);
        header.setLayoutParams(new PtrFrameLayout.LayoutParams(-1, -2));
        header.setPadding(0, BaseUtil.dip2px(15), 0, BaseUtil.dip2px(10));
        header.setPtrFrameLayout(layPtrFrame);

        layPtrFrame.setDurationToCloseHeader(1500);
        layPtrFrame.setHeaderView(header);
        layPtrFrame.addPtrUIHandler(header);
        layPtrFrame.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, viewRecycler, header);
            }

            @Override
            public void onRefreshBegin(final PtrFrameLayout frame) {
                collect_id = -1;
                requestUserCollectList(collect_id);
            }
        });

        postDelayed(runRequest, 500);
    }

    private Runnable runRequest = new Runnable() {
        @Override
        public void run() {
            layPtrFrame.autoRefresh();
        }
    };

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        removeCallbacks(runRequest);
    }

    private void requestUserCollectList(final long lastid) {
        if (reqLoad) return;
        reqLoad = true;

        if (collect_id > 0) adapter.refreshLoadState(true);
        PnwHttpManager.User.fansList(((BaseActivity) getContext()).TAG, lastid, new PnwOkCallbackAdapter<HttpRespData<List<User>>>() {
            @Override
            public void onResponse(HttpRespData<List<User>> response, boolean fresh) {
                super.onResponse(response, fresh);
                layPtrFrame.refreshComplete();
                reqLoad = false;
                fetchOver = false;
                collect_id = -1;

                if (response.errcode == C.http.RESULT_SUCCESS) {
                    if (response.data != null && response.data.size() > 0) {
                        fetchOver = response.data.size() < FansAdapter.FETCH_COUNT;

                        collect_id = response.data.get(response.data.size() - 1).collect_id;

                        boolean b = lastid < 0 ? adapter.set(response.data, fetchOver) : adapter.append(response.data, fetchOver);
                    } else {
                        BaseUtil.showToast(response.errmsg);
                        fetchOver = true;
                        boolean b = lastid > 0 ? adapter.refreshLoadState(false) : adapter.set(new ArrayList<User>(), true);
                    }
                } else {
                    if (fresh && response.errcode != C.http.RESULT_LOGIN_EXPIRE &&
                            response.errcode != C.http.RESULT_LOGIN_OFFLINE) {
                        BaseUtil.showToast(response.errmsg);
                    }

                    adapter.refreshLoadState(false);
                }
            }

            @Override
            public void onFailure(Request request, Exception e) {
                super.onFailure(request, e);
                layPtrFrame.refreshComplete();
                reqLoad = false;
                adapter.refreshLoadState(false);
            }
        });
    }

    private static class FansAdapter extends RecyclerAdapter {

        public class ViewHolderItem extends RecyclerView.ViewHolder implements OnClickListener {
            public ViewHolderItem(View view) {
                super(view);
                view.setOnClickListener(this);
            }

            private TextView txNickname, txContent, txAge, txHeight, txWeight;
            private ImageView imgAvatar, imgGender;
            private User user;

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(v.getContext(), ProfileInfoActivity.class);
                intent.putExtra(ProfileInfoActivity.EXTRA_SHOWN_USER_ID, user.id);
                v.getContext().startActivity(intent);
            }
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int type) {
            switch (type) {
                case Element.TYPE_ITEM:
                    View viewItem = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recycler_main_profile_concern, viewGroup, false);
                    ViewHolderItem vhItem = new ViewHolderItem(viewItem);
                    vhItem.imgAvatar = (ImageView) viewItem.findViewById(R.id.img_avatar);
                    vhItem.imgGender = (ImageView) viewItem.findViewById(R.id.img_gender);
                    vhItem.txNickname = (TextView) viewItem.findViewById(R.id.tx_nickname);
                    vhItem.txContent = (TextView) viewItem.findViewById(R.id.tx_content);
                    vhItem.txAge = (TextView) viewItem.findViewById(R.id.tx_age);
                    vhItem.txHeight = (TextView) viewItem.findViewById(R.id.tx_height);
                    vhItem.txWeight = (TextView) viewItem.findViewById(R.id.tx_weight);
                    return vhItem;
            }
            return super.onCreateViewHolder(viewGroup, type);
        }

        @Override
        public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder, final int position) {
            super.onBindViewHolder(viewHolder, position);
            Element e = elements.get(position);
            switch (e.type) {
                case Element.TYPE_ITEM:
                    ViewHolderItem vhItem = (ViewHolderItem) viewHolder;
                    User item = (User) e.element;
                    Glide.with(vhItem.itemView.getContext()).load(item.head_img_url).placeholder(R.mipmap.common_avatar_c_170)
                            .bitmapTransform(App.i().getCropCircleTransformation()).into(vhItem.imgAvatar);

                    vhItem.imgGender.setImageResource(item.sex == PnwHttpManager.Square.SQUARE_FILTER_GENDER_MALE
                            ? R.mipmap.concern_gender_male : R.mipmap.concern_gender_female);
                    vhItem.txNickname.setText(item.nickname);
                    vhItem.txContent.setText(item.intro);
                    vhItem.txAge.setText(item.age);
                    vhItem.txHeight.setText(item.height);
                    vhItem.txWeight.setText(item.weight);
                    vhItem.user = item;
                    break;
            }
        }
    }
}
